package com.secsbrain.deploy.biz.utils;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http请求工具类
 *
 * @author zhaoyi
 */
public class JenkinsHttpUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(JenkinsHttpUtils.class);
	
	private String baseUrl;
	
	private String userid;
	
	private String token;
	
	@SuppressWarnings("unused")
	private JenkinsHttpUtils(){
	}
	
	public JenkinsHttpUtils(String baseUrl, String userid, String token) {
		super();
		this.baseUrl = baseUrl;
		this.userid = userid;
		this.token = token;
	}


	/**
     * 功能描述: <br>
     * http post请求
     * 
     * @param url 请求URL
     * @param params 请求json参数
     * @return
     */
    public HttpResponse submitPost(String url, Map<String, String> params) {
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials(userid, token));  
        PostMethod method = new PostMethod(baseUrl+url);
        
    	HttpResponse httpResponse=new HttpResponse();
        try {
        	if(params!=null){
        		Set<Map.Entry<String, String>> entryseSet=params.entrySet();
            	for (Map.Entry<String, String> entry:entryseSet) {
            		method.setParameter(entry.getKey(), entry.getValue());
        		}
        	}
        	
            int statusCode = client.executeMethod(method);
            httpResponse.setStatusCode(statusCode);
            httpResponse.setLength(method.getResponseContentLength());
            httpResponse.setxMoreData(method.getResponseHeader("X-More-Data")==null?null:method.getResponseHeader("X-More-Data").getValue());
            httpResponse.setxTextSize(method.getResponseHeader("X-Text-Size")==null?null:method.getResponseHeader("X-Text-Size").getValue());
            
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                httpResponse.setResult(buffer.toString());
            }
        } catch (Exception e) {
        	logger.error("",e);
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return httpResponse;
    }

//    /**
//     * 功能描述: <br>
//     * http post请求
//     *
//     * @param url 请求URL
//     * @param params 请求json参数
//     * @return
//     */
//    public String postJsonRequest(String url, Map<String, String> params) {
//        HttpClient client = new HttpClient();
//        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
//        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
//        client.getParams().setAuthenticationPreemptive(true);
//        client.getState().setCredentials(AuthScope.ANY,
//                new UsernamePasswordCredentials(userid, token));
//        PostMethod method = new PostMethod(baseUrl+url);
//
//        try {
//            if(params!=null){
//                Set<Map.Entry<String, String>> entryseSet=params.entrySet();
//                for (Map.Entry<String, String> entry:entryseSet) {
//                    method.setParameter(entry.getKey(), entry.getValue());
//                }
//            }
//
//            int statusCode = client.executeMethod(method);
//            System.out.println("statusCode:"+statusCode);
//
//            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
//            if(CollectionUtils.isNotEmpty(list)){
//                StringBuffer buffer=new StringBuffer();
//                for(String str:list){
//                    buffer.append(str + "\n");
//                }
//                return buffer.toString();
//            }
//        } catch (Exception e) {
//            logger.error("",e);
//        } finally {
//            client.getHttpConnectionManager().closeIdleConnections(1);
//        }
//
//        return null;
//    }
    
    /**
     * 功能描述: <br>
     * 提交xml post请求
     * 
     * @param url 请求URL
     * @param xmlStr 请求json参数
     * @return
     */
    public String submitPostXml(String url, String xmlStr) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials(userid, token));  
        PostMethod method = new PostMethod(baseUrl+url);

        try {
        	RequestEntity requestEntity=new StringRequestEntity(xmlStr);
			method.setRequestEntity(requestEntity);
            int statusCode = client.executeMethod(method);
            logger.debug("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return buffer.toString();
            }
        } catch (Exception e) {
        	logger.error("",e);
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }

    public static String submitPostXml2(String url, String xmlStr,String pwd) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials("devops", pwd));
//                new UsernamePasswordCredentials("admin", "1109314b7168f35f06e7c93ab78b4a596b"));
        PostMethod method = new PostMethod(url);

        try {
        	RequestEntity requestEntity=new StringRequestEntity(xmlStr);
			method.setRequestEntity(requestEntity);
            int statusCode = client.executeMethod(method);
            logger.debug("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return buffer.toString();
            }
        } catch (Exception e) {
        	logger.error("",e);
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }
    
    /**
     * 功能描述: <br>
     * http get请求
     * 
     * @param url 请求URL
     * @return
     */
    public InputStream geXmlInputStream(String url) {
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials(userid, token));  
        GetMethod method = new GetMethod(baseUrl+url);
    	
        try {
            int statusCode = client.executeMethod(method);
            logger.debug("statusCode:"+statusCode);

         	return method.getResponseBodyAsStream();
        } catch (Exception e) {
        	logger.error("",e);
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }
        return null;
    }
    
    public static InputStream getXmlInputStream(String url) {
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials("admin", "116f4fce2caadfb3c99a7f864708bcbd85"));
        GetMethod method = new GetMethod(url);
    	
        try {
            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);

         	return method.getResponseBodyAsStream();
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }
        return null;
    }

	 /**
     * 功能描述: <br>
     * http get请求
     * 
     * @param url 请求URL
     * @param map 请求参数MAP
     * @return
     */
    public static String getRequest(String url, Map<String, Object> map) {
    	
    	HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials("devops", "11e20895187b8e5fc582d39298002aa83c"));
        GetMethod method = new GetMethod(url);
    	
        try {
            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return buffer.toString();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }
        return null;
    }
    
    /**
     * 功能描述: <br>
     * http post请求
     * 
     * @param url 请求URL
     * @param params 请求json参数
     * @return
     */
    public static String postRequest(String url, Map<String, String> params) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("devops", "11e20895187b8e5fc582d39298002aa83c"));
        PostMethod method = new PostMethod(url);

        try {
        	Set<Map.Entry<String, String>> entryseSet=params.entrySet();
        	for (Map.Entry<String, String> entry:entryseSet) {
        		method.setParameter(entry.getKey(), entry.getValue());
    		}
        	
            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return buffer.toString();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }
    
    /**
     * 功能描述: <br>
     * http post请求
     * 
     * @param url 请求URL
     * @param xmlStr 请求xmlStr参数
     * @return
     */
    public static String postXml(String url, String xmlStr) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        client.getParams().setAuthenticationPreemptive(true); 
        client.getState().setCredentials(AuthScope.ANY,   
                new UsernamePasswordCredentials("admin", "116f4fce2caadfb3c99a7f864708bcbd85"));
        PostMethod method = new PostMethod(url);

        try {
        	RequestEntity requestEntity=new StringRequestEntity(xmlStr);
			method.setRequestEntity(requestEntity);
            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                StringBuffer buffer=new StringBuffer();
                for(String str:list){
                    buffer.append(str + "\n");
                }
                return buffer.toString();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }

    /**
     * 功能描述: <br>
     * http put请求
     * 
     * @param url 请求URL
     * @param jsonStr 请求参数Json串
     * @return
     */
    public static String putRequest(String url, String jsonStr) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        PutMethod method = new PutMethod(url);

        try {
            RequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);

            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);

            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            return list.get(0);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }

    /**
     * 功能描述: <br>
     * http delete请求
     * 
     * @param url 请求URL
     * @return
     */
    public static String deleteRequest(String url) {
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接超时时间为5秒（连接初始化时间）
        DeleteMethod method = new DeleteMethod(url);

        try {
            int statusCode = client.executeMethod(method);
            System.out.println("statusCode:"+statusCode);
            List<String> list = IOUtils.readLines(method.getResponseBodyAsStream());
            if(CollectionUtils.isNotEmpty(list)){
                return list.get(0);
            }
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            client.getHttpConnectionManager().closeIdleConnections(1);
        }

        return null;
    }
}
